﻿using HalconDotNet;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Model.工具区域的扩展类;
using Halcon二次开发.View.工位监控画面;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows.Shapes;
using static System.Windows.Forms.LinkLabel;

namespace Halcon二次开发.Tools
{
    public class UtiyHalcon
    {
        /// <summary>
        /// 平移矩阵加旋转矩阵
        /// </summary>
        /// <param name="region">初始区域</param>
        /// <param name="current_row">当前模板行坐标</param>
        /// <param name="current_column">当前模板列坐标</param>
        /// <param name="current_phi">当前模板角度</param>
        /// <param name="firstModel_row">第一个模板行坐标</param>
        /// <param name="firstModel_column">第一个模板列坐标</param>
        /// <param name="firstModel_phi">第一个模板角度</param> 288 639 -3 711 366 -6
        /// <returns></returns>
        public static HObject MatrixCalculate(HObject region, double current_row, double current_column, double current_phi, double firstModel_row, double firstModel_column, double firstModel_phi)
        {
            // 检查是否需要变换
            if (Math.Abs(current_row - firstModel_row) < 1e-6 &&
                Math.Abs(current_column - firstModel_column) < 1e-6 &&
                Math.Abs(current_phi - firstModel_phi) < 1e-6)
            {
                return region; // 如果区域位置和角度未变，则直接返回
            }
            // 初始化单位矩阵并创建复合变换
            HOperatorSet.HomMat2dIdentity(out HTuple hv_HomMat2D);
            HOperatorSet.HomMat2dTranslate(hv_HomMat2D, current_row - firstModel_row, current_column - firstModel_column,
                out HTuple hv_HomMat2DTransform);
            HOperatorSet.HomMat2dRotate(hv_HomMat2DTransform, current_phi - firstModel_phi, current_row, current_column,
                out hv_HomMat2DTransform);

            // 复合仿射变换一次完成
            HObject ho_RegionAffineTrans = null;
            HOperatorSet.AffineTransRegion(region, out ho_RegionAffineTrans, hv_HomMat2DTransform, "nearest_neighbor");

            // 返回结果
            return ho_RegionAffineTrans;
        }
        public static HObject LineRotate(HObject region,double row,double column,double curren_phi,double first_phi)
        {
            //创建旋转矩阵
            HOperatorSet.HomMat2dIdentity(out HTuple hv_HomMat2DIdentity2);
            HOperatorSet.HomMat2dRotate(hv_HomMat2DIdentity2, curren_phi- 0,  row ,column,
                out HTuple hv_HomMat2DRotate);
            HOperatorSet.AffineTransRegion(region, out HObject ho_RegionAffineTrans,
                hv_HomMat2DRotate, "nearest_neighbor");//最终线段hobject  ho_RegionAffineTrans

            HOperatorSet.AreaCenter(ho_RegionAffineTrans,out HTuple are,out HTuple row1,out HTuple column1);
            return ho_RegionAffineTrans;
        }
    }
    public class DrawLayer
    {
        public HObject Region { get; set; } // ROI 区域对象
        public string Text { get; set; } // 显示的文字内容
        public HTuple TextPosition { get; set; } // 文字位置，使用 (row, column) 元组
        public string Color { get; set; } = "black"; // 绘制的颜色
        public string DrawType { get; set; } // 绘制类型，"region" 或 "text" 或 "cross"
        public int FontSize { get; set; } = 16; // 默认文字大小
        public HTuple CrossPosition { get; set; } // 交叉线位置 (row, column)
        public int CrossSize { get; set; } = 20; // 交叉线大小（线条长度）
    }
    public class HWindowContentManager
    {
        public readonly List<DrawLayer> drawQueue = new List<DrawLayer>();

        // 添加区域到绘制队列
        public void AddRegion(HObject region, string color = "green")
        {
            // 克隆传入的 HObject 区域对象，防止外部修改
            drawQueue.Add(new DrawLayer
            {
                Region = region.Clone(),
                Color = color,
                DrawType = "region"
            });
        }

        // 添加文字到绘制队列
        public void AddText(string text, HTuple position, string color = "green", int fontSize = 16)
        {
            drawQueue.Add(new DrawLayer
            {
                Text = text,
                TextPosition = position,
                Color = color,
                FontSize = fontSize, // 设置文字大小
                DrawType = "text"
            });
        }

        // 添加交叉线到绘制队列
        public void AddCross(HTuple position, int crossSize = 20, string color = "green")
        {
            drawQueue.Add(new DrawLayer
            {
                CrossPosition = position,
                CrossSize = crossSize,
                Color = color,
                DrawType = "cross"
            });
        }

        // 清理绘制队列并释放所有资源
        public void ClearDrawQueue()
        {
            foreach (var layer in drawQueue)
            {
                layer.Region?.Dispose(); // 释放每个区域的 HObject 资源\
                layer.CrossPosition?.Dispose();
                layer.TextPosition?.Dispose();
            }
            drawQueue.Clear(); // 清空队列
        }

        // 渲染绘制队列到指定窗体
        public void RenderToWindow(HSmartWindowControl targetWindow,HObject image)
        {
            try
            {
                HOperatorSet.SetDraw(targetWindow.HalconWindow, "margin");
                //先展示图片
                HOperatorSet.DispObj(image, targetWindow.HalconWindow);
               
                foreach (var layer in drawQueue)
                {
                    if (layer.DrawType == "region" && layer.Region != null)
                    {
                        // 设置颜色，线宽固定为 1
                        HOperatorSet.SetColor(targetWindow.HalconWindow, layer.Color);
                        HOperatorSet.DispObj(layer.Region, targetWindow.HalconWindow);
                    }
                    else if (layer.DrawType == "text" && !string.IsNullOrEmpty(layer.Text))
                    {

                        HOperatorSet.SetFont(targetWindow.HalconWindow, $"宋体-Bold-{layer.FontSize}");

                        // 设置颜色并绘制文字内容，支持指定位置和颜色
                        HOperatorSet.SetColor(targetWindow.HalconWindow, layer.Color);
                        HOperatorSet.DispText(targetWindow.HalconWindow, layer.Text, "image",
                                              layer.TextPosition[0], layer.TextPosition[1],
                        layer.Color, "box", 0);

                    }
                    else if (layer.DrawType == "cross" && layer.CrossPosition != null)
                    {
                        // 设置颜色后直接绘制交叉线，角度固定为 45
                        HOperatorSet.SetColor(targetWindow.HalconWindow, layer.Color);
                        // 使用 DispCross 绘制交叉线，固定角度为 45
                        HOperatorSet.DispCross(targetWindow.HalconWindow, layer.CrossPosition[0],
                                                layer.CrossPosition[1], layer.CrossSize, 45); // 固定 45 度
                    }
                }
            }
            catch(Exception ex)
            {

            }
            
        }
        /// <summary>
        /// 抛出异常调用这个
        /// </summary>
        /// <param name="targetWindow"></param>
        /// <param name="image"></param>
        public void RenderToWindowNg(HSmartWindowControl targetWindow, HObject image)
        {
            try
            {
                //先展示图片
                HOperatorSet.DispObj(image, targetWindow.HalconWindow);
                targetWindow.SetFullImagePart();
                foreach (var layer in drawQueue)
                {
                    if (layer.DrawType == "region" && layer.Region != null)
                    {
                        // 设置颜色，线宽固定为 1
                        HOperatorSet.SetColor(targetWindow.HalconWindow, layer.Color);
                        HOperatorSet.SetLineWidth(targetWindow.HalconWindow, 1); // 固定线宽为 1
                        HOperatorSet.DispObj(layer.Region, targetWindow.HalconWindow);
                    }
                    else if (layer.DrawType == "text" && !string.IsNullOrEmpty(layer.Text))
                    {
                        HOperatorSet.SetFont(targetWindow.HalconWindow, $"宋体-Bold-{layer.FontSize}");

                        // 设置颜色并绘制文字内容，支持指定位置和颜色
                        HOperatorSet.SetColor(targetWindow.HalconWindow, layer.Color);
                        HOperatorSet.DispText(targetWindow.HalconWindow, layer.Text, "image",
                                              layer.TextPosition[0], layer.TextPosition[1],
                        layer.Color, "box", 0);
                    }
                    else if (layer.DrawType == "cross" && layer.CrossPosition != null)
                    {
                        // 设置颜色后直接绘制交叉线，角度固定为 45
                        HOperatorSet.SetColor(targetWindow.HalconWindow, layer.Color);
                        // 使用 DispCross 绘制交叉线，固定角度为 45
                        HOperatorSet.DispCross(targetWindow.HalconWindow, layer.CrossPosition[0],
                                                layer.CrossPosition[1], layer.CrossSize, 45); // 固定 45 度
                    }
                }
            }
            catch
            {

            }
        }
    }
}
